package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper UserMapper;
    @Autowired
    private RoleMapper roleMapper;

    public List<User> list() {
        List<User> userList = UserMapper.findAll();
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //第一步 向sys_user表中存储数据
        UserMapper.save(user);
        //拿到自增长后返回的主键
        long userId = user.getId();
        System.out.println("自增长后返回的主键userId===========" + userId);
        //第二步 向sys_user_role 关系表中存储多条数据
        for (long roleId : roleIds) {
            UserMapper.saveUserRoleRel(userId, roleId);
        }
    }

    public void del(Long userId) {
        //1、删除sys_user_role关系表
        UserMapper.delUserRoleRel(userId);
        //2、删除sys_user表
        UserMapper.del(userId);
    }

    public User login(String username, String password) {
        try {
            User user = UserMapper.findByUsernameAndPassword(username, password);
            return user;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public User findById(String id) {
        try {
            User user = UserMapper.findById(Integer.parseInt(id));
            return user;
        } catch (Exception e) {
            return null;
        }

    }

}
